import { Redis } from 'ioredis'

export class CacheService {
    private redis: Redis

    constructor() {
        this.redis = new Redis(process.env.REDIS_URL!)

        this.redis.on('error', (error) => {
            console.error('Redis连接错误:', error)
        })
    }

    // 设置缓存
    async set(key: string, value: any, expires?: number): Promise<void> {
        try {
            const data = JSON.stringify(value)
            if (expires) {
                await this.redis.setex(key, expires, data)
            } else {
                await this.redis.set(key, data)
            }
        } catch (error) {
            console.error('设置缓存失败:', error)
            throw error
        }
    }

    // 获取缓存
    async get<T>(key: string): Promise<T | null> {
        try {
            const data = await this.redis.get(key)
            return data ? JSON.parse(data) : null
        } catch (error) {
            console.error('获取缓存失败:', error)
            throw error
        }
    }

    // 删除缓存
    async delete(key: string): Promise<void> {
        try {
            await this.redis.del(key)
        } catch (error) {
            console.error('删除缓存失败:', error)
            throw error
        }
    }

    // 设置哈希表
    async hset(key: string, field: string, value: any): Promise<void> {
        try {
            const data = JSON.stringify(value)
            await this.redis.hset(key, field, data)
        } catch (error) {
            console.error('设置哈希表失败:', error)
            throw error
        }
    }

    // 获取哈希表字段
    async hget<T>(key: string, field: string): Promise<T | null> {
        try {
            const data = await this.redis.hget(key, field)
            return data ? JSON.parse(data) : null
        } catch (error) {
            console.error('获取哈希表失败:', error)
            throw error
        }
    }

    // 删除哈希表字段
    async hdel(key: string, field: string): Promise<void> {
        try {
            await this.redis.hdel(key, field)
        } catch (error) {
            console.error('删除哈希表失败:', error)
            throw error
        }
    }
}

// 导出单例
export const cacheService = new CacheService() 